<template>
  <div
    class="login-container"
    :style="{
      'background-image': 'url(./public/img/login/login_bj.jpg)'
    }"
  >
    <div class="login_box">
      <div class="logoTitle">
        <img :src="`./public/img/logo.jpg`">
        <p class="loginName">用户登录</p>
      </div>
      <el-form
        ref="loginForm"
        :model="loginForm"
        class="login-form"
        autocomplete="on"
        label-position="left"
      >
        <!-- :rules="loginRules" -->
        <el-form-item prop="username">
          <span class="svg-container">
            <svg-icon icon-class="user" />
          </span>
          <el-input
            ref="username"
            v-model.trim="loginForm.username"
            placeholder="用户名"
            name="username"
            type="text"
            tabindex="1"
          />
        <!--           autocomplete="on" -->
        </el-form-item>

        <el-tooltip
          v-model="capsTooltip"
          content="Caps lock is On"
          placement="right"
          manual
        >
          <el-form-item prop="password">
            <span class="svg-container">
              <svg-icon icon-class="password" />
            </span>
            <el-input
              :key="passwordType"
              ref="password"
              v-model.trim="loginForm.password"
              :type="passwordType"
              placeholder="密码"
              name="password"
              tabindex="2"
              autocomplete="on"
              @keyup.native="checkCapslock"
              @blur="capsTooltip = false"
              @keyup.enter.native="handleLogin"
            />
            <span
              class="show-pwd"
              @click="showPwd"
            >
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
        </el-tooltip>
        <el-button
          :loading="loading"
          type="primary"
          class="linerBtnSure"
          style="width: 100%;margin-top: 30px;height: 50px;"
          @click.native.prevent="handleLogin"
        >
          登 录
        </el-button>
        <div class="jyllq_wrap">
          <span class="jyllq">建议浏览器：</span>
          <span class="explorer_item"><i class="iconfont iconliulanqi" /><span>IE10+</span></span>
          <span class="explorer_item"><i class="iconfont iconchrome" /><span>谷歌</span></span>
          <span class="explorer_item"><i class="iconfont iconhuohu" /><span>火狐</span></span>
        </div>
      </el-form>
    </div>
    <div class="copyright">
      ©2019 <br>
    </div>
  </div>
</template>

<script>
import { validUsername } from "@/utils/validate";
import { routeObj, layout } from "@/router/route.js";
import { resetRouter } from "@/router/index.js";
export default {
  name: "Login",
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error("请输入正确的用户名"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("密码不能小于6个字符"));
      } else {
        callback();
      }
    };
    return {
      loginForm: {
        username: "",
        password: ""
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername }
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword }
        ]
      },
      passwordType: "password",
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {}
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true
    }
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    if (this.loginForm.username === "") {
      this.$refs.username.focus();
    } else if (this.loginForm.password === "") {
      this.$refs.password.focus();
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    checkCapslock({ shiftKey, key } = {}) {
      if (key && key.length === 1) {
        if (
          (shiftKey && (key >= "a" && key <= "z")) ||
          (!shiftKey && (key >= "A" && key <= "Z"))
        ) {
          this.capsTooltip = true;
        } else {
          this.capsTooltip = false;
        }
      }
      if (key === "CapsLock" && this.capsTooltip === true) {
        this.capsTooltip = false;
      }
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    /**
     * @name deepMenu
     * @description
     * @author cjs1992
     * @date 2019-09-27 14:51:17
     */
    deepMenu(list, arr) {
      list.map((item) => {
        if (
          arr.findIndex((vo) => {
            return item.route === vo.route;
          }) === -1
        ) {
          arr.push(item);
        }
        if (item.children && item.children.length) {
          this.deepMenu(item.children, arr);
        }
      });
    },
    handleLogin() {
      if (this.loginForm.username.length == 0) {
        this.$message({
          type: "warning",
          message: "请输入正确的用户名!"
        });
        return;
      }
      if (this.loginForm.password.length < 6) {
        this.$message({
          type: "warning",
          message: "密码不能小于6个字符!"
        });
        return;
      }
      // 清除上次登录的数据
      this.$store.dispatch("tagsView/delAllViews");
      this.$refs.loginForm.validate(async valid => {
        if (valid) {
          this.loading = true;
          try {
            const res = await this.$store.dispatch("user/login", this.loginForm);
            console.log("res", res);
            this.$store.dispatch("user/setInfo", {
              name: res.data.userName,
              roles: res.data.roles,
              role_id: res.data.roleId,
              buttons: res.data.buttons,
              id: res.data.id
            });
            window.localStorage.setItem("deptId", res.data.zzjgId);
            this.$message({
              type: "success",
              message: "登录成功!",
              duration: 1000
            });
            this.loading = false;
            const checkLogin = await this.$store.dispatch("user/checkLogin");
            this.$store.dispatch("user/setInfo", {
              name: checkLogin.data.userName,
              roles: checkLogin.data.roles,
              role_id: checkLogin.data.roleId,
              buttons: checkLogin.data.buttons,
              id: checkLogin.data.id,
              userInfo: {
                id: String(checkLogin.data.id),
                userCode: checkLogin.data.userCode,
                userName: checkLogin.data.userName
              },
              userDept: (checkLogin.data.deptList || []).map((vo) => {
                return {
                  id: vo.zzjgId,
                  zzjg_code: vo.zzjgCode,
                  zzjg_name: vo.zzjgName
                };
              })
            });
            // 请求路由
            this.$store.dispatch("user/getMenu", {
              appKey: window.$appKey
            }).then((res) => {
              try {
                const list = [];
                this.deepMenu(res.data, list);
                const asyncRouteList = [];
                for (const item of list) {
                  if (!item.route || !routeObj[item.route]) {
                    continue;
                  }
                  asyncRouteList.push({
                    path: item.route,
                    component: layout,
                    children: [
                      {
                        path: item.route,
                        component: routeObj[item.route]["component"],
                        name: routeObj[item.route]["name"],
                        meta: { title: item.name, icon: item.icon, noCache: false }
                      }
                    ]
                  });
                }
                // let asyncRouteList = list.map((item) => {
                //   return {
                //     path: item.route,
                //     component: layout,
                //     children: [
                //       {
                //         path: item.route,
                //         component: routeObj[item.route]['component'],
                //         name: routeObj[item.route]['name'],
                //         meta: { title: item.name, icon: item.icon }
                //       }
                //     ]
                //   }
                // })
                resetRouter();
                this.$router.addRoutes(asyncRouteList);
                this.$router.push({
                  path: this.redirect || "/welcome",
                  query: this.otherQuery
                });
              } catch (error) {
                console.log(error);
              }
            }).catch((err) => {
              // 报错，调到welcome页面
              this.$router.push({
                path: "/welcome",
                query: this.otherQuery
              });
            });
          } catch (error) {
            this.loading = false;
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    }
    // afterQRScan() {
    //   if (e.key === 'x-admin-oauth-code') {
    //     const code = getQueryObject(e.newValue)
    //     const codeMap = {
    //       wechat: 'code',
    //       tencent: 'code'
    //     }
    //     const type = codeMap[this.auth_type]
    //     const codeName = code[type]
    //     if (codeName) {
    //       this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
    //         this.$router.push({ path: this.redirect || '/' })
    //       })
    //     } else {
    //       alert('第三方登录失败')
    //     }
    //   }
    // }
  }
};
</script>

<style lang="scss" scope>
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $bg;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 80%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $bg;
      height: 47px;
      caret-color: $bg;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px #fff inset !important;
        -webkit-text-fill-color: $bg !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid #eee;
    // background: rgba(0, 0, 0, 0.1);
    background:#fff;
    color: #454545;
    border-radius: 38px;
    //  border: 1px solid transparent;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  background-repeat: no-repeat;
  background-position: right;
  // background: url(../../../public/public/img/login/login_bj.jpg) no-repeat  right;
  min-height: 100%;
  width: 100%;
  background-color: #fff;
  background-size: auto 100%;
  overflow: hidden;
  .login_box{
    padding: 25px 20px;
    text-align: center;
    position: absolute;
    left: 218px;
    top: 50%;
    transform: translateY(-250px);
    width: 408px;
    text-align: center;
    background: rgba(255,255,255,0.8);
    border-radius: 20px;
  }
 .logoTitle img{
     display: inline-block;
    //  width:312px;
  }
  .logoTitle p{
    padding:20px 0 60px;
    line-height: 30px;
    font-size: 22px;
    color: #555;
  }
  .login-form {
    position: relative;
    // width: 520px;
    max-width: 100%;
    // padding: 160px 35px 0;
    margin: 0 auto;
    // overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }

    .set-language {
      color: #fff;
      position: absolute;
      top: 3px;
      font-size: 18px;
      right: 0px;
      cursor: pointer;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }
  .linerBtnSure{
    border-radius: 26px;
    border: 1px solid transparent;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    background: -webkit-gradient(to right, from(#6ad7de), to(#66df9a));
    background: linear-gradient(to  right, #6ad7de, #66df9a);
    filter: progid:DXImageTransform.Microsoft.gradient(GradientType=1, startColorstr=#6ad7de, endColorstr=#66df9a);
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient (GradientType=1, startColorstr=#6ad7de, endColorstr=#66df9a)";
    /deep/ span {
      font-size: 16px;
    }
  }
  .copyright{
    position: absolute;
    bottom: 60px;
    left: 218px;
    width: 408px;
    text-align: center;
    color: #5d5d5d;
    line-height: 20px;
  }
  @media screen and (max-height: 660px) {
    .copyright {
      bottom: 20px
    }
    .loginName {
      padding-bottom: 30px !important;
    }
    .linerBtnSure  {
      margin-top: 10px !important;
    }
  }
  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
.jyllq_wrap {
  color: #656565;
  padding-top: 30px;
  .explorer_item {
    margin-left: 6px;
  }
  .iconfont {
    color: #60d1a7;
    margin-right: 3px;
  }
}
</style>
